const blogModel = require('./model/blogModel');
const blogTypeModel = require('./model/blogTypeModel');

// 添加文章
module.exports.addBlogDao = async function (newBlogInfo) {
    console.log(newBlogInfo);
    try {
        const result = await blogModel.create(newBlogInfo);
        // console.log(result);
        return result.dataValues
    } catch (error) {
        console.log(error);
    }
}
// 获取文章列表(分页)
module.exports.getBlogListDao = async function (pageInfo) {
    if (pageInfo.categoryId && pageInfo.categoryId !== '-1') {
        // 根据分类信息分页查询
        return await blogModel.findAndCountAll({
            // 关联
            include: [
                {
                    model: blogTypeModel,
                    // 别名
                    as: 'category',
                    where: {
                        id: Number(pageInfo.categoryId)
                    }
                }
            ],
            offset: (pageInfo.page * 1 - 1) * pageInfo.limit,
            limit: pageInfo.limit * 1,
            order: [
                ['createDate', 'desc']
            ]
        })
    } else {
        // 直接分页查询
        return await blogModel.findAndCountAll({
            include: [
                {
                    model: blogTypeModel,
                    as: 'category'
                }
            ],
            offset: (pageInfo.page * 1 - 1) * pageInfo.limit,
            limit: pageInfo.limit * 1,
            order: [
                ['createDate', 'desc']
            ]
        })
    }
}
// 获取某篇文章
module.exports.getBlogByIdDao = async function (id) {
    return await blogModel.findByPk(id, {
        include: [
            {
                model: blogTypeModel,
                as: 'category'
            }
        ]
    })
}
// 修改文章
module.exports.updateBlogDao = async function (id, newBlogInfo) {
    await blogModel.update(newBlogInfo, {
        where: {
            id
        }
    })
    return await blogModel.findByPk(id)
}
// 删除文章
module.exports.deleteBlogDao = async function (id) {
    return await blogModel.destroy({
        where: {
            id
        }
    })
}